package com.hobart.learning.lagou.edu.IPersistence.config;

import com.hobart.learning.lagou.edu.IPersistence.pojo.Configuration;
import com.hobart.learning.lagou.edu.IPersistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author ：hobart
 * @date ：Created in 2020-11-10 16:39
 * @description：
 * @modified By：
 * @version: $
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

//        List<Element> selectList = rootElement.selectNodes("//select");

        List<Element> selectList = rootElement.selectNodes("select|insert|update|delete");
        selectList.forEach( element -> {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);

            StringBuilder key = new StringBuilder();
            key.append(namespace).append(".").append(id);
            configuration.getMappedStatementMap().put(key.toString(), mappedStatement);
        });


    }




}
